from yhlz_backtest.strategy.base import Strategy
from abc import abstractmethod

class RB(Strategy):
    def __init__(self, feed, broker):
        super().__init__(feed, broker)

    def next(self):
        pass

    @abstractmethod
    def process_feed(self, df):
        pass

    def __init__(self, feed, broker, **kwargs):
        super().__init__(feed, broker)
        self.current_instrument = kwargs['init_instrument']
        self.main_con_map = {'01': '05', '05': '10', '10': '01'}
        self.pos_now = None
        self.open_interest_after = None
        self.open_interest = None

    def change_contract(self, bars):
        """
        更换交易日的时间检查是否应当换合约
        目前采用的逻辑是，如果要缓合约，将现在的合约平掉，等下一个合约开仓。
        """
        f_contract = self.joint_instrument(self.current_instrument)
        self.open_interest = bars.getBar(self.current_instrument).get_open_interest()
        try:
            self.open_interest_after = bars.getBar(f_contract).get_open_interest()
        except KeyError:
            return

        if self.open_interest_after > self.open_interest * 0.7:
            self.info(f'换合约：{self.current_instrument}->{f_contract}')
            if self.pos_now:
                self.pos_now.exitMarket()
                self.pos_now = None
            self.current_instrument = f_contract

    def joint_instrument(self, instrument):
        """
        根据main_con_map,拼接下一个标的的代码
        """
        f_contract = self.main_con_map[instrument.strip('RB')[2:]]
        if f_contract == "01":  # 新年，前面的十年要就加一
            future_contract = 'RB' + str(int(instrument[-4:-2]) + 1) + f_contract
        else:
            future_contract = instrument[:-2] + f_contract
        return future_contract